﻿using Microsoft.WindowsAzure.ServiceRuntime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data;

using Services;
using Domain;



namespace WebRole1
{
	public partial class ViewTopic : System.Web.UI.Page
	{
		//variables for the smileys
		string frown;
		//string wink;
		string puh;
		string smile;
		string biggrin;
		//string bye;
		//string cry;
		//string emo;
		//string kiss;
		string sad;


		private void Page_Init(object sender, System.EventArgs e)
		{
			this.EnableViewState = false;
		}


		public System.Drawing.Color Color1
		{
			get
			{
				return System.Drawing.Color.White;
			}
		}

		public System.Drawing.Color Color2
		{
			get
			{
				return System.Drawing.Color.FromArgb(238, 238, 238);
			}
		}


		public System.Drawing.Color ColorQuote
		{
			get
			{
				return System.Drawing.Color.FromArgb(180, 180, 180);
			}
		}



		protected void Page_Load(object sender, EventArgs e)
		{
			
			frown = RoleEnvironment.GetConfigurationSettingValue("Smiley_Frown");
			//wink = RoleEnvironment.GetConfigurationSettingValue("Smiley_Wink");
			puh = RoleEnvironment.GetConfigurationSettingValue("Smiley_Puh");
			smile = RoleEnvironment.GetConfigurationSettingValue("Smiley_Smile");
			biggrin = RoleEnvironment.GetConfigurationSettingValue("Smiley_BigGrin");
			//bye = RoleEnvironment.GetConfigurationSettingValue("Smiley_Bye");
			//cry = RoleEnvironment.GetConfigurationSettingValue("Smiley_Cry");
			//emo = RoleEnvironment.GetConfigurationSettingValue("Smiley_Emo");
			//kiss = RoleEnvironment.GetConfigurationSettingValue("Smiley_Kiss");
			sad = RoleEnvironment.GetConfigurationSettingValue("Smiley_Sad");

			decimal start = System.DateTime.Now.Ticks;

			btnSubmit.Attributes.Add("onclick", "this.disabled=true;" + ClientScript.GetPostBackEventReference(btnSubmit, null).ToString());

			btnBold.Attributes.Add("onclick", "btnBold_Click(document.getElementById('" + txtNewMsg.ClientID + "')); return false;");
			btnBold.Attributes.Add("OnMouseOver", "this.className='hand';");

			btnItalic.Attributes.Add("onclick", "btnItalic_Click(document.getElementById('" + txtNewMsg.ClientID + "')); return false;");
			btnItalic.Attributes.Add("OnMouseOver", "this.className='hand';");

			btnImage.Attributes.Add("onclick", "btnImage_Click(document.getElementById('" + txtNewMsg.ClientID + "')); return false;");
			btnImage.Attributes.Add("OnMouseOver", "this.className='hand';");

			btnHyperlink.Attributes.Add("onclick", "btnHyperlink_Click(document.getElementById('" + txtNewMsg.ClientID + "')); return false;");
			btnHyperlink.Attributes.Add("OnMouseOver", "this.className='hand';");



			HttpCookie aCookie = Request.Cookies["ForumSettings"];
			if (aCookie != null)
			{
				if (aCookie["Username"] != null)
				{
					lblUsername.Visible = false;
					txtUsername.Visible = false;
					lblLeaveEmpty.Visible = false;
				}
			}



			Int64 topicID;
			Int16 page;
			bool isLoggedIn;
			string userID;
			string urlTitle;

			

			if (!IsPostBack)
			{
				GetVariables(out topicID, out page, out isLoggedIn, out userID, out urlTitle);
				ShowPosts(topicID, urlTitle, page, 25, isLoggedIn, userID);
			}

			this.Form.Action = this.Request.RawUrl;

			decimal end = System.DateTime.Now.Ticks;

			lblPageloadDuration.Text = "page loaded in " +  ((end - start) / 10000000).ToString("n3") + " seconds";
		}

		private void GetVariables(out Int64 topicID, out Int16 page, out bool isLoggedIn, out string userID, out string urltitle)
		{
			topicID = 0;
			page = 0;

			if (HttpContext.Current.Request.QueryString["id"] != null)
			{
				topicID = Int64.Parse(HttpContext.Current.Request.QueryString["id"].ToString());
			}
			else if (HttpContext.Current.Request.QueryString["ID"] != null)
			{
				topicID = Int64.Parse(HttpContext.Current.Request.QueryString["ID"].ToString());
			}
			else
			{
				Response.Redirect("index");
			}

			if (HttpContext.Current.Request.QueryString["page"] != null)
			{
				page = Int16.Parse(HttpContext.Current.Request.QueryString["page"].ToString());
			}
			else if (HttpContext.Current.Request.QueryString["Page"] != null)
			{
				page = Int16.Parse(HttpContext.Current.Request.QueryString["Page"].ToString());
			}
			else if (HttpContext.Current.Request.QueryString["PAGE"] != null)
			{
				page = Int16.Parse(HttpContext.Current.Request.QueryString["PAGE"].ToString());
			}
			else
			{
				Response.Redirect("index");
			}


			if (HttpContext.Current.Request.QueryString["title"] == null)
			{
				urltitle = "";
			}
			else
			{
				urltitle = HttpContext.Current.Request.QueryString["title"].ToString();

			}
			
			
			isLoggedIn = false;
			userID = "";


			HttpCookie aCookie = Request.Cookies["ForumSettings"];
			if (aCookie != null)
			{
				if (aCookie["UserID"] != null)
				{
					isLoggedIn = true;
					userID = aCookie["UserID"].ToString();
				}
			}

		}



		/// <summary>
		/// 
		/// </summary>
		/// <param name="topicID"></param>
		/// <param name="urlTitle">The title of the topic as it's shown in the url, like "this-is-the-topictitle"</param>
		/// <param name="pageNr">number of the page that is currently being viewed</param>
		/// <param name="pageSize">number of posts that fit on a page</param>
		/// <param name="isLoggedIn">Is the current user logged in, yes or no?</param>
		/// <param name="loggedInUserID">the ID of the logged in user. If not logged in, this will be "0"</param>
		private void ShowPosts(Int64 topicID, string urlTitle, Int16 pageNr, Int16 pageSize, bool isLoggedIn, string loggedInUserID)
		{
			//Always begin with a clear screen
			tblMessages.Rows.Clear();

			//the role of the currently logged in user
			string currentUserRole = "";

			//Get the posts of the topic and the page
			PostingService postingServ = new PostingService();
			IList<Post> postings = postingServ.getPostings(topicID, pageNr, pageSize, loggedInUserID, ref currentUserRole);

			//If there are 0 posts, the user has requested a topic or page that doesn't exist
			//or something has gone wrong
			if (postings.Count == 0)
				Response.Redirect("~/index");


			//Set the variables for the breadcrumb at the top of the screen
			//The breadcrumb looks like this: 'index / subforum / topictitle'
			hlSubforum.Text = postings[0].SubforumName;
			hlSubforum.NavigateUrl = "~/viewSubForum.aspx?id=" + postings[0].SubforumID.ToString();
			lblTopicTitle.Text = postings[0].TopicTitle;
			//string urlTitle = "";

			//Set the title of the browser
			Title = postings[0].TopicTitle;

			//Set the meta data
			HtmlMeta metaDesc = new HtmlMeta();
			metaDesc.Name = "description";
			metaDesc.Content = postings[0].TopicTitle;
			Page.Header.Controls.Add(metaDesc);

			HtmlMeta metaKey = new HtmlMeta();
			metaKey.Name = "keywords";
			metaKey.Content = postings[0].TopicTitle;
			Page.Header.Controls.Add(metaKey);



			int backcolorType = 2;
			foreach (Post p in postings)
			{
				//Show each post on screen
				ShowPosts(topicID, isLoggedIn, loggedInUserID, urlTitle, backcolorType, p, currentUserRole);
			}



			//Show the page numbers, so the user can browse the another page in the topic
			Int64 pagecount = ((postings[0].TopicPostCount - 1) / pageSize) + 1;
			ShowPagenumbers(topicID, pageNr, pageSize, pagecount, urlTitle);




			//
			// Add to Twitter
			//
			hlAddToTwitter.NavigateUrl = Server.HtmlEncode("http://twitter.com/home?status=" + postings[0].TopicTitle + " http://www.esc7.nl/topic/" + topicID.ToString() + "/1/" + postings[0].UrlTitle);

			hlAddToFacebook.NavigateUrl = Server.HtmlEncode("http://www.facebook.com/share.php?u=http://www.esc7.nl/topic/" + topicID.ToString() + "/1/" + postings[0].UrlTitle);

			TableCell cellShare = CreateCell_ShareThisTopic(topicID, postings);
			TableCell cellTwitter = CreateHyperlink_AddToTwitter(topicID, postings);
			TableCell cellFacebook = CreateHyperlink_AddToFacebook(topicID, postings);

			TableRow rowFooterShare = new TableRow();
			rowFooterShare.HorizontalAlign = HorizontalAlign.Left;
			
			rowFooterShare.Cells.Add(cellShare);
			rowFooterShare.Cells.Add(cellTwitter);
			rowFooterShare.Cells.Add(cellFacebook);

			tblShare.Rows.Add(rowFooterShare);
		}




		private void ShowPagenumbers(Int64 topicID, Int16 pageNr, Int16 pageSize, Int64 pagecount, string urlTitle)
		{
			Label labelPages = new Label();
			labelPages.Text = "Pages ";
			divPages.Controls.Add(labelPages);



			//Right now I'm adding a new table the the table tblMessages.
			//In that subtable I write the pagenumbers.
			//This is a difficult way. Rewrite this so only a DIV or something is used.


			//Create a new footer row, for the pagenumbers
			Table tblFooterPages = new Table();
			tblFooterPages.BorderWidth = Unit.Pixel(0);
			TableRow rowFooterPages = new TableRow();
			rowFooterPages.BorderWidth = Unit.Pixel(0);
			tblFooterPages.Rows.Add(rowFooterPages);

			TableRow trPagesFooter = NewTableRow(1);

			TableCell tcPagesFooter = NewTableCell();
			tcPagesFooter.ColumnSpan = 2;
			tcPagesFooter.HorizontalAlign = HorizontalAlign.Left;

			Label lblFooter = new Label();
			lblFooter.Text = "Pages ";

			TableCell cellFooterPage1 = new TableCell();
			cellFooterPage1.Controls.Add(lblFooter);

			rowFooterPages.Cells.Add(cellFooterPage1);

			tcPagesFooter.Controls.Add(tblFooterPages);

			trPagesFooter.Cells.Add(tcPagesFooter);









			Label lblHeader = new Label();
			lblHeader.Text = "Pages ";


			Table tblHeaderPages = new Table();

			TableRow rowHeaderPages = new TableRow();
			tblHeaderPages.Rows.Add(rowHeaderPages);

			TableCell cellPage1 = new TableCell();
			cellPage1.Controls.Add(lblHeader);

			rowHeaderPages.Cells.Add(cellPage1);

			tblHeader.Rows[1].Cells[0].Controls.Add(tblHeaderPages);









			int i = 1;
			while (i <= pagecount)
			{
				TableCell cellPage = new TableCell();
				cellPage.HorizontalAlign = HorizontalAlign.Center;

				TableCell cellPageFooter = new TableCell();
				cellPageFooter.HorizontalAlign = HorizontalAlign.Center;

				if (i == pageNr) //if i == currentpage, show only the pagenumber, and no hyperlink
				{
					Label lblDivPageNr = new Label();
					lblDivPageNr.CssClass = "Default";
					lblDivPageNr.Text = i.ToString();
					lblDivPageNr.BorderColor = System.Drawing.Color.Black;
					lblDivPageNr.Width = Unit.Pixel(15);
					lblDivPageNr.BorderStyle = BorderStyle.Solid;
					lblDivPageNr.BorderWidth = Unit.Pixel(1);
					lblDivPageNr.Style.Add("TEXT-ALIGN", "center");
					divPages.Controls.Add(lblDivPageNr);

					Label lblDivEmpty = new Label();
					lblDivEmpty.CssClass = "Default";
					lblDivEmpty.Text = "";
					lblDivEmpty.Width = Unit.Pixel(2);
					lblDivEmpty.BorderStyle = BorderStyle.None;
					lblDivEmpty.BorderWidth = Unit.Pixel(0);
					lblDivEmpty.Style.Add("TEXT-ALIGN", "center");
					divPages.Controls.Add(lblDivEmpty);



					Label lblPageHeader = new Label();
					lblPageHeader.CssClass = "Default";
					lblPageHeader.Text = i.ToString();
					lblPageHeader.BorderColor = System.Drawing.Color.Black;
					lblPageHeader.Width = Unit.Pixel(15);
					lblPageHeader.BorderStyle = BorderStyle.Solid;
					lblPageHeader.BorderWidth = Unit.Pixel(1);
					cellPage.Controls.Add(lblPageHeader);
					rowHeaderPages.Cells.Add(cellPage);

					//Label lblPageFooter = new Label();
					//lblPageFooter.CssClass = "Default";
					//lblPageFooter.Text = i.ToString();
					//lblPageFooter.BorderColor = System.Drawing.Color.Black;
					//lblPageFooter.Width = Unit.Pixel(15);
					//lblPageFooter.BorderStyle = BorderStyle.Solid;
					//lblPageFooter.BorderWidth = Unit.Pixel(1);
					//cellPageFooter.Controls.Add(lblPageFooter);
					//rowFooterPages.Cells.Add(cellPageFooter);
				}
				else
				{
					HyperLink lblDivPageNr = new HyperLink();
					lblDivPageNr.CssClass = "Default";
					lblDivPageNr.Text = i.ToString();
					lblDivPageNr.NavigateUrl = "~/topic/" + topicID.ToString() + "/" + i.ToString() + "/" + urlTitle;
					lblDivPageNr.BorderColor = System.Drawing.Color.Black;
					lblDivPageNr.Width = Unit.Pixel(15);
					lblDivPageNr.BorderStyle = BorderStyle.Solid;
					lblDivPageNr.BorderWidth = Unit.Pixel(1);
					lblDivPageNr.Style.Add("TEXT-ALIGN", "center");
					divPages.Controls.Add(lblDivPageNr);

					Label lblDivEmpty = new Label();
					lblDivEmpty.CssClass = "Default";
					lblDivEmpty.Text = "";
					lblDivEmpty.Width = Unit.Pixel(2);
					lblDivEmpty.BorderStyle = BorderStyle.None;
					lblDivEmpty.BorderWidth = Unit.Pixel(0);
					lblDivEmpty.Style.Add("TEXT-ALIGN", "center");
					divPages.Controls.Add(lblDivEmpty);


					HyperLink hlPageHeader = new HyperLink();
					hlPageHeader.CssClass = "Default";
					HyperLink hlPageFooter = new HyperLink();

					hlPageHeader.NavigateUrl = "~/topic/" + topicID.ToString() + "/" + i.ToString() + "/" + urlTitle;
					hlPageHeader.Width = Unit.Pixel(15);
					hlPageHeader.BorderColor = System.Drawing.Color.Black;
					hlPageHeader.BorderStyle = BorderStyle.Solid;
					hlPageHeader.BorderWidth = Unit.Pixel(1);

					//hlPageFooter.NavigateUrl = "~/topic/" + topicID.ToString() + "/" + i.ToString() + "/" + urlTitle;
					//hlPageFooter.Width = Unit.Pixel(15);
					//hlPageFooter.BorderColor = System.Drawing.Color.Black;
					//hlPageFooter.BorderStyle = BorderStyle.Solid;
					//hlPageFooter.BorderWidth = Unit.Pixel(1);

					hlPageHeader.Text = i.ToString();
					//hlPageFooter.Text = i.ToString();

					cellPage.Controls.Add(hlPageHeader);
					rowHeaderPages.Cells.Add(cellPage);

					//cellPageFooter.Controls.Add(hlPageFooter);
					//rowFooterPages.Cells.Add(cellPageFooter);
				}

				i++;
			}

			//if the current page is not the last page
			//add the hyperlink 'next page' to the pagenumbers
			if (pageNr != pagecount)
			{
				HyperLink lblDivPageNr = new HyperLink();
				lblDivPageNr.CssClass = "Default";
				lblDivPageNr.Text = "next page";
				lblDivPageNr.NavigateUrl = "~/topic/" + topicID.ToString() + "/" + (pageNr + 1).ToString() + "/" + urlTitle;
				lblDivPageNr.BorderColor = System.Drawing.Color.Black;
				lblDivPageNr.Width = Unit.Pixel(75);
				lblDivPageNr.BorderStyle = BorderStyle.None;
				lblDivPageNr.BorderWidth = Unit.Pixel(1);
				lblDivPageNr.Style.Add("TEXT-ALIGN", "center");
				divPages.Controls.Add(lblDivPageNr);

				Label lblDivEmpty = new Label();
				lblDivEmpty.CssClass = "Default";
				lblDivEmpty.Text = "";
				lblDivEmpty.Width = Unit.Pixel(2);
				lblDivEmpty.BorderStyle = BorderStyle.None;
				lblDivEmpty.BorderWidth = Unit.Pixel(0);
				lblDivEmpty.Style.Add("TEXT-ALIGN", "center");
				divPages.Controls.Add(lblDivEmpty);




				HyperLink hlPageHeader = new HyperLink();
				hlPageHeader.CssClass = "Default";
				//HyperLink hlPageFooter = new HyperLink();

				hlPageHeader.NavigateUrl = "~/topic/" + topicID.ToString() + "/" + (pageNr + 1).ToString() + "/" + urlTitle;
				hlPageHeader.Width = Unit.Pixel(75);
				hlPageHeader.BorderColor = System.Drawing.Color.Black;
				hlPageHeader.BorderStyle = BorderStyle.None;
				hlPageHeader.BorderWidth = Unit.Pixel(1);

				//hlPageFooter.NavigateUrl = "~/topic/" + topicID.ToString() + "/" + (pageNr + 1).ToString() + "/" + urlTitle;
				//hlPageFooter.Width = Unit.Pixel(75);
				//hlPageFooter.BorderColor = System.Drawing.Color.Black;
				//hlPageFooter.BorderStyle = BorderStyle.None;
				//hlPageFooter.BorderWidth = Unit.Pixel(1);

				hlPageHeader.Text = "next page";
				//hlPageFooter.Text = "next page";

				TableCell cellPage = new TableCell();
				cellPage.Controls.Add(hlPageHeader);
				rowHeaderPages.Cells.Add(cellPage);

				//TableCell cellPageFooter = new TableCell();
				//cellPageFooter.Controls.Add(hlPageFooter);
				//rowFooterPages.Cells.Add(cellPageFooter);
			}


			//trPagesFooter.Cells.Add(tcPagesFooter);
			//tblMessages.Rows.Add(trPagesFooter);
		}

		private string ShowPosts(Int64 topicID, bool isLoggedIn, string loggedInUserID, string urlTitle, int backcolorType, Post p, string currentUserRole)
		{
			urlTitle = p.UrlTitle;

			//postcount = int.Parse(row["TotalCount"].ToString());
			TableRow tr = NewTableRow(backcolorType);

			TableCell tc = NewTableCell();
			tc.VerticalAlign = VerticalAlign.Top;
			tc.Width = Unit.Pixel(150);

			AddPosterInfo(tc, p.UserID.ToString(), p.Username, p.UserSubtitle, p.UserAvatar, p.UserTwitter, p.UserLevelName, backcolorType);

			tr.Cells.Add(tc);

			tc = NewTableCell();
			tc.VerticalAlign = VerticalAlign.Top;
			tc.Width = Unit.Pixel(700);
			tc.HorizontalAlign = HorizontalAlign.Justify;

			string userID = "";
			if (p.UserID.ToString() != "")
			{
				userID = p.UserID.ToString();
			}

			AddPostingHeader(tc, topicID, p.ID.ToString(), p.PostedOn, p.Username, userID, backcolorType, isLoggedIn, loggedInUserID, p.TopicTitle, p.UrlTitle, currentUserRole);

			AddPostingContent(tc, p.Content, backcolorType);

			tr.Cells.Add(tc);

			tblMessages.Rows.Add(tr);

			if (p.UserSignature.Trim() != "")
			{
				AddPostingSignature(p.UserSignature, backcolorType);
			}

			tr = NewTableRow(1);
			tc = NewTableCell();
			tc.ColumnSpan = 3;
			tc.Height = Unit.Pixel(10);
			tr.Cells.Add(tc);
			tblMessages.Rows.Add(tr);
			return urlTitle;
		}

		private TableCell CreateCell_ShareThisTopic(Int64 topicID, IList<Post> postings)
		{
			TableCell cell = NewTableCell();
			cell.Height = Unit.Pixel(18);
			cell.VerticalAlign = VerticalAlign.Middle;
			cell.Wrap = false;
			cell.HorizontalAlign = HorizontalAlign.Left;

			Label hlTwitter = new Label();
			hlTwitter.Width = Unit.Pixel(95);
			hlTwitter.Text = "Share this topic ";
			cell.Controls.Add(hlTwitter);
			return cell;
		}


		private TableCell CreateHyperlink_AddToTwitter(Int64 topicID, IList<Post> postings)
		{
			TableCell cell = NewTableCell();
			cell.Width = Unit.Pixel(20);
			cell.Height = Unit.Pixel(18);
			//cell.VerticalAlign = VerticalAlign.Bottom;
			cell.Wrap = false;
			cell.HorizontalAlign = HorizontalAlign.Left;

			HyperLink hlTwitter = new HyperLink();
			hlTwitter.NavigateUrl = Server.HtmlEncode("http://twitter.com/home?status=" + postings[0].TopicTitle + " http://www.esc7.nl/topic/topic/" + topicID.ToString() + "/1/" + postings[0].UrlTitle);
			hlTwitter.ImageUrl = "AddToTwitter.jpg";
			hlTwitter.ToolTip = "add topic to Twitter";
			cell.Controls.Add(hlTwitter);
			return cell;
		}



		private TableCell CreateHyperlink_AddToFacebook(Int64 topicID, IList<Post> postings)
		{
			TableCell cell = NewTableCell();
			cell.Width = Unit.Pixel(20);
			cell.Height = Unit.Pixel(18);
			//cell.VerticalAlign = VerticalAlign.Bottom;
			cell.Wrap = false;
			cell.HorizontalAlign = HorizontalAlign.Left;

			HyperLink hlTwitter = new HyperLink();
			hlTwitter.NavigateUrl = Server.HtmlEncode("http://www.facebook.com/share.php?u=http://www.esc7.nl/topic/" + topicID.ToString() + "/1/" + postings[0].UrlTitle);
			hlTwitter.ImageUrl = "facebook.gif";
			hlTwitter.ToolTip = "add topic to Facebook";
			cell.Controls.Add(hlTwitter);
			return cell;
		}



		private void AddPostingContent(TableCell tc, string message, int backcolorType)
		{
			tc.BorderStyle = BorderStyle.None;

			Table tbl = NewTable();

			TableCell cell = NewTableCell();

			message = Server.HtmlDecode(message);

			message = message.Replace("&gt;:(", "<img src=\"" + frown + "\" alt=\"frown\" />"); //code to create this smiley:  >:(
			message = message.Replace("&gt;:|", "<img src=\"" + frown + "\" alt=\"frown\" />"); //code to create this smiley:  >:|
			message = message.Replace("&gt;:{", "<img src=\"" + frown + "\" alt=\"frown\" />"); //code to create this smiley:  >:{
			//message = message.Replace(";)", "<img src=\"" + wink + "\" alt=\"wink\" />");
			message = message.Replace(":p", "<img src=\"" + puh + "\" alt=\"puh\" />");
			message = message.Replace(":P", "<img src=\"" + puh + "\" alt=\"puh\" />");
			message = message.Replace(":)", "<img src=\"" + smile + "\" alt=\"smile\" />");
			message = message.Replace(":D", "<img src=\"" + biggrin + "\" alt=\"biggrin\" />");
			//message = message.Replace(":hi", "<img src=\"" + bye + "\" alt=\"bye\" />");
			//message = message.Replace(":'(", "<img src=\"" + cry + "\" alt=\"cry\" />");
			//message = message.Replace(":')", "<img src=\"" + emo + "\" alt=\"emo\" />");
			//message = message.Replace(":*", "<img src=\"" + kiss + "\" alt=\"kiss\" />");
			//message = message.Replace("_O-", "<img src=\"" + schater + "\" alt=\"schater\" />");
			message = message.Replace(":(", "<img src=\"" + sad + "\" alt=\"sad\" />");

			cell.Text = message;

			TableRow rowQuote = NewTableRow(backcolorType);
			rowQuote.Cells.Add(cell);

			tbl.Rows.Add(rowQuote);

			tc.Controls.Add(tbl);
		}



		private Table NewTable()
		{
			Table tbl = new Table();
			tbl.CellPadding = 0;
			tbl.CellSpacing = 0;

			return tbl;
		}


		private TableRow NewTableRow(int backcolorType)
		{
			TableRow row = new TableRow();
			row.BorderStyle = BorderStyle.None;
			row.Width = Unit.Pixel(700);
			row.HorizontalAlign = HorizontalAlign.Justify;


			if (backcolorType == 1)
			{
				row.BackColor = Color1;
				row.BorderColor = Color1;

			}
			else if (backcolorType == 2)
			{
				row.BackColor = Color2;
				row.BorderColor = Color2;
			}
			else if (backcolorType == 99)
			{
				row.BackColor = ColorQuote;
				row.BorderColor = ColorQuote;
			}

			return row;
		}


		private TableCell NewTableCell()
		{
			TableCell cell = new TableCell();
			cell.BorderStyle = BorderStyle.None;
			return cell;
		}



		private void AddPostingSignature(string message, int backcolorType)
		{
			TableRow tr = NewTableRow(backcolorType);

			tr.Font.Size = FontUnit.Point(8);

			TableCell tc = NewTableCell();

			tr.Cells.Add(tc);


			tc = NewTableCell();


			tc.ColumnSpan = 4;
			Label lblMessage = new Label();

			System.Text.StringBuilder sb = new System.Text.StringBuilder();
			sb.AppendLine("__________________________________________________________<br/>");
			sb.AppendLine();
			sb.AppendLine(message);
			lblMessage.Text = sb.ToString();
			lblMessage.Height = Unit.Pixel(50);
			tc.Controls.Add(lblMessage);
			tr.Cells.Add(tc);

			tblMessages.Rows.Add(tr);
		}

		private void AddPosterInfo(TableCell tc, string userID, string postedByName, string subtitle, string avatar, string twitter, string levelname, int backcolorType)
		{
			Table tbl = NewTable();
			TableRow row = NewTableRow(backcolorType);
			row.Width = Unit.Pixel(150);
			row.BackColor = System.Drawing.Color.FromArgb(204, 204, 204);
			TableCell cell = NewTableCell();
			Label lbl = new Label();
			cell.Controls.Add(lbl);
			cell.Height = Unit.Pixel(20);
			cell.Width = Unit.Pixel(150);
			row.Cells.Add(cell);
			tbl.Rows.Add(row);

			row = NewTableRow(backcolorType);

			cell = NewTableCell();
			cell.Wrap = false;


			if (userID != "")
			{
				HyperLink hlPostedBy = new HyperLink();
				hlPostedBy.Font.Bold = true;
				hlPostedBy.CssClass = "H6";
				hlPostedBy.Text = postedByName;
				hlPostedBy.NavigateUrl = "profile.aspx?user=" + postedByName;

				
				cell.Controls.Add(hlPostedBy);

				Label lblEmpty = new Label();
				lblEmpty.Text = "&nbsp&nbsp";
				cell.Controls.Add(lblEmpty);
			}
			else
			{
				Label lblPostedBy = new Label();
				lblPostedBy.Font.Bold = true;
				lblPostedBy.Text = postedByName;
				lblPostedBy.CssClass = "H6";
				cell.Controls.Add(lblPostedBy);

				Label lblEmpty = new Label();
				lblEmpty.Text = "&nbsp&nbsp";
				cell.Controls.Add(lblEmpty);
			}

			row.Cells.Add(cell);

			tbl.Rows.Add(row);



			////Subtitle
			//row = NewTableRow(backcolorType);

			//cell = NewTableCell();

			//Label lblSubtitle = new Label();
			//lblSubtitle.Text = subtitle;

			//cell.Controls.Add(lblSubtitle);

			//row.Cells.Add(cell);

			//tbl.Rows.Add(row);


			//Level
			row = NewTableRow(backcolorType);

			cell = NewTableCell();

			Label lblLevel = new Label();
			lblLevel.Text = levelname;
			lblLevel.CssClass = "H7";

			cell.Controls.Add(lblLevel);

			row.Cells.Add(cell);

			tbl.Rows.Add(row);




			//Avatar
			if (avatar != "")
			{
				row = NewTableRow(backcolorType);

				cell = NewTableCell();

				Image imgAvatar = new Image();
				imgAvatar.Width = Unit.Pixel(64);
				imgAvatar.Height = Unit.Pixel(64);
				imgAvatar.ImageUrl = avatar;

				cell.Controls.Add(imgAvatar);

				row.Cells.Add(cell);

				tbl.Rows.Add(row);
			}



			//Twitter
			if (twitter != "")
			{
				row = NewTableRow(backcolorType);

				cell = NewTableCell();

				ImageButton imgTwitter = new ImageButton();
				imgTwitter.ImageUrl = "~/twitterAdd.gif";
				imgTwitter.PostBackUrl = "http://www.twitter.com/" + twitter;
				imgTwitter.AlternateText = "See on twitter";
				imgTwitter.ToolTip = "See on twitter";

				cell.Controls.Add(imgTwitter);

				row.Cells.Add(cell);

				tbl.Rows.Add(row);
			}


			tc.Controls.Add(tbl);
		}

		private void AddPostingHeader(
			TableCell tc,
			Int64 topicID,
			string postID,
			string postedOn,
			string postedByName,
			string postedByID,
			int backcolorType,
			bool isLoggedIn,
			string loggedInUserID,
			string title,
			string urltitle,
			string currentUserRole
			)
		{
			tc.Width = Unit.Pixel(600);

			Table tbl = NewTable();
			//tbl.GridLines = GridLines.Both;
			tbl.Font.Size = FontUnit.Point(8);

			TableRow row = NewTableRow(backcolorType);

			row.BackColor = System.Drawing.Color.FromArgb(204, 204, 204);
			row.BorderStyle = BorderStyle.None;

			row.Width = Unit.Pixel(800);


			//
			// LABEL
			// So we can jump to the position of this post
			//
			TableCell cell = NewTableCell();
			cell = NewTableCell();
			cell.Text = "<a name=\"" + postID.ToString() + "\"></a>";
			row.Cells.Add(cell);



			//
			// PROFILE
			//
			cell = NewTableCell();
			cell = NewTableCell();
			cell.HorizontalAlign = HorizontalAlign.Left;
			cell.Width = Unit.Pixel(150);
			cell.Height = Unit.Pixel(18);
			cell.Wrap = false;

			Label lblPostedBy = new Label();
			lblPostedBy.Text = postedOn;

			cell.Controls.Add(lblPostedBy);
			row.Cells.Add(cell);





			cell = NewTableCell();
			cell.Width = Unit.Pixel(584);
			cell.Height = Unit.Pixel(18);
			cell.Wrap = false;
			row.Cells.Add(cell);



			//
			// DELETE
			//
			cell = NewTableCell();
			cell.Width = Unit.Pixel(100);
			cell.Height = Unit.Pixel(18);
			cell.Wrap = false;
			cell.HorizontalAlign = HorizontalAlign.Right;

			if (currentUserRole == "root")
			{
				HyperLink hlDelete = new HyperLink();
				hlDelete.NavigateUrl = "DeletePost.aspx?topic=" + topicID.ToString() + "&postid=" + postID.ToString() + "&urltitle=" + urltitle;
				hlDelete.Text = "(Delete)";
				hlDelete.ForeColor = System.Drawing.Color.FromArgb(30, 150, 0);
				cell.Controls.Add(hlDelete);

				//
				// SPACE
				//
				Label lblSpace = new Label();
				lblSpace.Text = " ";
				cell.Controls.Add(lblSpace);
			}






			//
			// EDIT
			//
			//cell = NewTableCell();
			cell.Width = Unit.Pixel(100);
			cell.Height = Unit.Pixel(18);
			cell.Wrap = false;
			cell.HorizontalAlign = HorizontalAlign.Right;

			if (isLoggedIn)
			{
				if (postedByID == loggedInUserID)
				{
					HyperLink hlEdit = new HyperLink();
					hlEdit.NavigateUrl = "WritePost.aspx?Topic=" + topicID.ToString() + "&Edit=" + postID.ToString() + "&urltitle=" + urltitle;
					hlEdit.Text = "(Edit)";
					hlEdit.ForeColor = System.Drawing.Color.FromArgb(30, 150, 0);

					cell.Controls.Add(hlEdit);

					//
					// SPACE
					//
					Label lblSpace = new Label();
					lblSpace.Text = " ";
					cell.Controls.Add(lblSpace);
				}
			}





			//
			// QUOTE
			//
			HyperLink hlQuote = new HyperLink();
			hlQuote.NavigateUrl = "WritePost.aspx?Topic=" + topicID.ToString() + "&ReplyTo=" + postID.ToString() + "&urltitle=" + urltitle;
			hlQuote.ForeColor = System.Drawing.Color.FromArgb(30, 150, 0);
			hlQuote.Text = "(Quote)";


			cell.Controls.Add(hlQuote);
			row.Cells.Add(cell);

			tbl.Rows.Add(row);

			tc.Controls.Add(tbl);
		}

		void btnDelete_Click(object sender, EventArgs e)
		{
			Int64 postID = Int64.Parse(e.ToString());
			Services.PostingService pServ = new PostingService();
			pServ.DeletePost(postID, 3);
		}

		void lblEdit_Command(object sender, CommandEventArgs e)
		{
			Response.Redirect("Profile.aspx?ID=" + e.CommandArgument.ToString());
		}



		private class ContentPart
		{
			public ContentPart(string type, string content)
			{
				Type = type;
				Content = content;
			}

			public string Type { get; set; }
			public string Content { get; set; }
		}

		protected void btnPreview_Click(object sender, EventArgs e)
		{
			lblPreview.Visible = true;
			string message = Server.HtmlEncode(txtNewMsg.Text);

			PostingService pServ = new PostingService();
			lblPreview.Text = pServ.ParseMessage(message);

			Int64 topicID;
			Int16 page;
			bool isLoggedIn;
			string userID;
			string urlTitle;

			GetVariables(out topicID, out page, out isLoggedIn, out userID, out urlTitle);
			ShowPosts(topicID, urlTitle, page, 25, isLoggedIn, userID);
		}



		protected void btnSubmit_Click(object sender, EventArgs e)
		{
			string postID = "";
			int postCount = 0;

			string username = "";
			Int64 topicID;
			Int16 page;
			bool isLoggedIn;
			string userID;
			string urlTitle;

			HttpCookie aCookie = Request.Cookies["ForumSettings"];
			if (aCookie != null)
			{
				if (aCookie["Username"] != null)
				{
					username = aCookie["Username"];
				}
			}

			if (username == "")
			{
				if (txtUsername.Text.Trim() == "")
				{
					username = "Anonymous";
				}
				else
				{
					username = txtUsername.Text.Trim();
				}
			}





			if (txtNewMsg.Text.Trim() == "")
			{
				lblError.Text = "Type een bericht dat u wilt plaatsen";

				GetVariables(out topicID, out page, out isLoggedIn, out userID, out urlTitle);
				ShowPosts(topicID, urlTitle, page, 25, isLoggedIn, userID);

				return;
			}

			topicID = Int64.Parse(HttpContext.Current.Request.QueryString["id"].ToString());

			PostingService postingServ = new PostingService();

			string message = Server.HtmlEncode(txtNewMsg.Text);

			try
			{

				string ipaddress = Request.ServerVariables["REMOTE_ADDR"].ToString();

				postingServ.InsertPosting(message, topicID, username, Utils.GetUserID(Request), ipaddress, out postID, out postCount);
			}
			catch (Exception ex)
			{
				GetVariables(out topicID, out page, out isLoggedIn, out userID, out urlTitle);
				ShowPosts(topicID, urlTitle, page, 25, isLoggedIn, userID);

				lblError.Text = ex.Message;
			}



			GetVariables(out topicID, out page, out isLoggedIn, out userID, out urlTitle);
			//ShowPosts(topicID, page, 25, isLoggedIn, userID);

			int lastPageNR = ((postCount - 1) / 25) + 1;
			Response.Redirect("~/topic/" + topicID + "/" + lastPageNR + "/" + urlTitle + "#" + postID);
			//Response.Redirect("ViewTopic.aspx?id=" + topicID + "&page=1");
		}




		private string GetUsername()
		{
			if (Request.Cookies["ForumSettings"] != null)
			{
				if (Request.Cookies["ForumSettings"]["Username"] != null)
				{
					return Request.Cookies["ForumSettings"]["Username"].ToString();
				}
			}

			return "";
		}
	}


}